package com.reverse;

public class demo {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode tail = new ListNode(5);

        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = tail;
        tail.next = null;

        ListNode head2 = head;
        while (head2 != null){
            System.out.print(head2.val);
            head2 = head2.next;
            if (head2 != null) System.out.print("->");
        }

        System.out.println();
        head2 = reverse(head,1, 5);
        while (head2 != null){
            System.out.print(head2.val);
            head2 = head2.next;
            if (head2 != null) System.out.print("->");
        }
    }

    public static ListNode reverse(ListNode head, int m , int n){
        if (head == null || m >= n) return head;

        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        head = dummy;

        for (int i = 1; i < m; i++) {
            head = head.next;
        }
        ListNode prevM = head;
        ListNode mNode = prevM.next;
        ListNode nNode = mNode;
        ListNode postN = nNode.next;

        for (int i = m; i < n; i++) { //翻转链表
            ListNode next = postN.next;
            postN.next = nNode;
            nNode = postN;
            postN = next;
        }

        prevM.next = nNode;
        mNode.next = postN;
        return dummy.next;
    }
}
